package com.pds.web.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pds.common.core.domain.entity.SysRole;
import com.pds.common.core.domain.entity.SysUser;
import com.pds.common.utils.DateUtils;
import com.pds.common.utils.SecurityUtils;
import com.pds.web.app.mapper.AppMonitorTaskMapper;
import com.pds.web.app.service.IAppMonitorTaskService;
import com.pds.web.monitor.domain.PdsMonitorTask;
import com.pds.web.monitor.domain.PdsMonitorTaskAnalysis;
import com.pds.web.monitor.domain.PdsMonitorTaskSampling;
import com.pds.web.monitor.mapper.PdsMonitorTaskAnalysisMapper;
import com.pds.web.monitor.mapper.PdsMonitorTaskMapper;
import com.pds.web.monitor.mapper.PdsMonitorTaskSamplingMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
@Service
public class AppMonitorTaskServiceImpl implements IAppMonitorTaskService {

    private static Logger log = LoggerFactory.getLogger(AppMonitorTaskServiceImpl.class);

    @Autowired
    PdsMonitorTaskSamplingMapper pdsMonitorTaskSamplingMapper;
    @Autowired
    PdsMonitorTaskMapper pdsMonitorTaskMapper;
    @Autowired
    AppMonitorTaskMapper appMonitorTaskMapper;
    @Autowired
    PdsMonitorTaskAnalysisMapper pdsMonitorTaskAnalysisMapper;


    /**
     * 首页待办查询
     * @param type week本周、month本月、year本年
     * @return
     */
    @Override
    public Map getTaskList(String type) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Set<String> role = user.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
        Map map = DateUtils.getTimePeriod(type);
        map.put("userId",user.getUserId());
        int totalNum = 0; //总数
        int ongoingNum = 0; //进行中
        int approveNum = 0 ;//审批中
        int finishNum = 0; //完成
        Map resultMap = new HashMap(5);
        List<Map> task = new ArrayList<>();
        if (role.contains("enSupervise")) {
            //企业-采样监督员
            //查询企业-采样监督员指定时间段内任务
            task = appMonitorTaskMapper.getSuperviseTaskByTime(map);
            map.put("startTime",null);
            map.put("endTime",null);
            List<Map> taskList = appMonitorTaskMapper.getSuperviseTaskByTime(map);
            if(taskList!= null && taskList.size() > 0) {
                taskList = taskList.stream().filter(item -> item.get("superviseStatus").toString().equals("2")).collect(Collectors.toList());
            }
            resultMap.put("taskList", taskList);
        }else if(role.contains("testSampler") || role.contains("testAnalyst")) {
            //检测机构-采样员、检测机构-分析员
            task = appMonitorTaskMapper.getTestTaskByTime(map);
            map.put("startTime",null);
            map.put("endTime",null);
            List<Map> taskList = appMonitorTaskMapper.getTestTaskByTime(map);
            if(taskList!= null && taskList.size() > 0) {
                if (role.contains("testSampler") && role.contains("testAnalyst")) {
                    //防止兼两职情况
                    //采样表状态4为已完成，分析表状态2为已完成，其他为待办
                    String status = "1,2";
                    taskList = taskList.stream().filter(item -> status.contains(item.get("status").toString()) &&
                            (!"4".equals(item.get("samplingStatus").toString()) ||
                                    !"2".equals(item.get("analysisStatus").toString()))
                    ).collect(Collectors.toList());
                } else if (role.contains("testSampler")) {
                    String status = "1";
                    taskList = taskList.stream().filter(item -> status.contains(item.get("status").toString()) &&
                            !"4".equals(item.get("samplingStatus").toString())
                    ).collect(Collectors.toList());
                } else if (role.contains("testAnalyst")) {
                    String status = "2";
                    taskList = taskList.stream().filter(item -> status.contains(item.get("status").toString()) &&
                            !"2".equals(item.get("analysisStatus").toString())
                    ).collect(Collectors.toList());
                }
            }
            resultMap.put("taskList", taskList);
        }else if(role.contains("epbTaskLeader")||role.contains("admin")) {
            //环境局-检测任务负责人	，待审核
            //app端没有功能，此查询仅用于web，故只查待办列表
            List<Map> taskList = appMonitorTaskMapper.getEpbTask(map);
            resultMap.put("taskList", taskList);
        }

        if(task!=null && task.size()>0){
            approveNum = (int) task.stream().filter(item -> item.get("status").toString().equals("4")).count();
            finishNum = (int) task.stream().filter(item -> item.get("status").toString().equals("5")).count();
            totalNum = task.size();
            ongoingNum = totalNum - approveNum - finishNum;
        }
        resultMap.put("totalNum",totalNum);
        resultMap.put("ongoingNum",ongoingNum);
        resultMap.put("approveNum",approveNum);
        resultMap.put("finishNum",finishNum);
        return resultMap;
    }


    /**
     * 现场采样留痕
     *
     * @param map  -taskId 任务ID
     *             -place 位置经纬度
     *             -type 类型：1采样签到、2发起确认请求、3监督核对、4仪器选择、5采样签退
     *             -deviceIds 仪器id
     *             -fileId 拍照拍照id
     */
    @Override
    public void sampling(Map map) throws Exception {
        Long taskId = Long.parseLong(String.valueOf(map.get("taskId")));
        String type = String.valueOf(map.get("type"));
        String fileId = String.valueOf(map.get("fileId"));
        String place = String.valueOf(map.get("place"));
        log.info("现场采样留痕：taskId={},type={}",taskId,type);

        SysUser user = SecurityUtils.getLoginUser().getUser();
        Set<String> role = user.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
        //只有企业-采样监督员enSupervise可以确认
        //只有检测机构-采样员testSampler可以签到、发起确认、选择仪器、签退
        if (("3".equals(type) && !role.contains("enSupervise")) ||
                ("1,2,4,5".contains(type)) && !role.contains("testSampler")) {
            throw new Exception("您没有权限，请联系管理员");
        }
        PdsMonitorTask task = pdsMonitorTaskMapper.queryById(taskId);
        //任务权限检测
        checkTask(task,user);
        if (!"1".equals(task.getStatus())) {
            throw new Exception("采样已结束，不能修改");
        }
        QueryWrapper<PdsMonitorTaskSampling> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", task.getId());
        PdsMonitorTaskSampling taskSampling = pdsMonitorTaskSamplingMapper.selectOne(wrapper);
        PdsMonitorTaskSampling pdsMonitorTaskSampling = new PdsMonitorTaskSampling();
        pdsMonitorTaskSampling.setTaskId(task.getId());
        Date createTime = DateUtils.parseDate(DateUtils.getTime());
        //1采样签到、2发起确认请求、3监督核对、4仪器选择、5采样签退
        if("1".equals(type)){ //1采样签到
            if (taskSampling.getSamplingBeginImgId() == null) {
                pdsMonitorTaskSampling.setSamplingBeginImgId(fileId);
                pdsMonitorTaskSampling.setSamplingDateBegin(createTime);
                pdsMonitorTaskSampling.setSamplingBeginPlace(place);
                pdsMonitorTaskSampling.setStatus(1);
            }else {
                throw new Exception("已签到，不能重复签到");
            }
        }else if("2".equals(type)){ //2发起确认请求
            pdsMonitorTaskSampling.setStatus(2);
        }else if("3".equals(type)){ //3监督核对
            //企业-采样监督员,上传监督信息
            pdsMonitorTaskSampling.setSuperviseImgId(fileId);
            pdsMonitorTaskSampling.setSupervisePlace(place);
            pdsMonitorTaskSampling.setSuperviseTime(createTime);
            pdsMonitorTaskSampling.setStatus(3);
            pdsMonitorTaskSamplingMapper.updateByTaskId(pdsMonitorTaskSampling);
            return;
        }else if("4".equals(type)){ //4仪器选择
            if(taskSampling.getStatus().intValue()==4){
                throw new Exception("已签退，不能修改仪器");
            }
            if(ObjectUtil.isEmpty(map.get("deviceIds"))){
                throw new Exception("采样仪器不能为空，请先选择采样仪器");
            }
            pdsMonitorTaskSampling.setDeviceIds(String.valueOf(map.get("deviceIds")));
        }else if("5".equals(type)){ //5采样签退
            if (taskSampling.getSamplingEndImgId() == null) {
                if(taskSampling.getStatus().intValue()!=3){
                    throw new Exception("监督员未核对信息，请等待");
                }else if(taskSampling.getDeviceIds()==null){
                    throw new Exception("采样仪器不能为空，请先选择采样仪器");
                }
                pdsMonitorTaskSampling.setSamplingEndImgId(fileId);
                pdsMonitorTaskSampling.setSamplingDateEnd(createTime);
                pdsMonitorTaskSampling.setSamplingEndPlace(place);
                pdsMonitorTaskSampling.setStatus(4);
            }else{
                throw new Exception("已签退，不能重复签退");
            }
        }else{
            throw new Exception("非法操作，请退出重试");
        }

        pdsMonitorTaskSampling.setUpdateBy(user.getNickName());
        pdsMonitorTaskSamplingMapper.updateByTaskId(pdsMonitorTaskSampling);
    }


    /**
     * 实验室分析、现场留痕
     * @param map
     *          -taskId 任务ID
     *          -place 位置经纬度
     *          -type 类型：1签到、2、添加仪器、3签退
     *          -deviceIds 仪器id
     *          -fileId 拍照拍照id
     */
    @Override
    public void analysis(Map map) throws Exception {
        Long taskId = Long.parseLong(String.valueOf(map.get("taskId")));
        String type = String.valueOf(map.get("type"));
        String fileId = String.valueOf(map.get("fileId"));
        String place = String.valueOf(map.get("place"));
        log.info("实验室分析现场留痕：taskId={},type={}",taskId,type);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        PdsMonitorTask task = pdsMonitorTaskMapper.queryById(taskId);
        //任务权限检测
        checkTask(task,user);
        QueryWrapper<PdsMonitorTaskAnalysis> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", task.getId());
        PdsMonitorTaskAnalysis analysisDB = pdsMonitorTaskAnalysisMapper.selectOne(wrapper);
        PdsMonitorTaskAnalysis temp = new PdsMonitorTaskAnalysis();
        temp.setTaskId(taskId);
        temp.setUpdateBy(user.getNickName());
        //开始结束记录，不能修改
        if("1".equals(type)){
            //签到
            if(analysisDB.getAnalysisBeginImgId()!=null){
                throw new Exception("已签到，不能重复签到");
            }
            temp.setAnalysisBeginImgId(fileId);
            temp.setAnalysisBeginLocation(place);
            temp.setStatus(1);
        }else if("2".equals(type)){
            //仪器
            if(ObjectUtil.isEmpty(map.get("deviceIds"))) {
                throw new Exception("仪器不能为空");
            }
            temp.setDeviceIds(String.valueOf(map.get("deviceIds")));
        }else if("3".equals(type)) {
            //签退
            if(ObjectUtil.isEmpty(analysisDB.getDeviceIds())) {
                throw new Exception("仪器不能为空");
            }
            if(analysisDB.getAnalysisEndImgId()!=null){
                throw new Exception("已签退，不能重复签退");
            }
            temp.setAnalysisEndImgId(fileId);
            temp.setAnalysisEndLocation(place);
            temp.setStatus(2);
        }else{
            throw new Exception("非法操作，请退出重试");
        }
        pdsMonitorTaskAnalysisMapper.updateByTaskId(temp);
    }

    /**
     * 检测任务权限
     * @param task
     * @param user
     */
    private void checkTask(PdsMonitorTask task, SysUser user) throws Exception {
        if(task==null){
            throw new Exception("此任务不存在");
        }
        if(task.getCompanyId().intValue()!= user.getDept().getOrganizationId().intValue() &&
                task.getOrganizationId().intValue()!= user.getDept().getOrganizationId().intValue())  {
            throw new Exception("此任务不属于您公司，您无权操作");
        }
    }
}
